#include "worker.h"
#include "threadPool.h"

// 小火车协议
//typedef struct train_s{
//    int length;
//    char data[1000];
//}train_t;
int tidArrInit(tidArr_t *ptidArr,int workerNum)
{
    // 申请内存，存储每一个子线程的tid
    ptidArr->arr = (pthread_t *)calloc(workerNum,sizeof(pthread_t));
    ptidArr->workerNum = workerNum;
    return 0;
}

void *threadFunc(void *arg)
{
    threadPool_t *pthreadPool = (threadPool_t * )arg;
    
    // 子线程接收任务
    while(1)
    {
        pthread_mutex_lock(&pthreadPool->mutex);
        while(pthreadPool->taskQueue.queueSize <= 0)// 如果主线程与子线程的共享队列没有元素，则子线程则要等待，知道主线程入队
        {
            pthread_cond_wait(&pthreadPool->cond,&pthreadPool->mutex);
        }
        int netfd = pthreadPool->taskQueue.pFront->netfd;
        deQueue(&pthreadPool->taskQueue);
        pthread_mutex_unlock(&pthreadPool->mutex);
        // 上述子线程通过”异步“访问共享队列获取到与服务器通信的netfd，接下来客户端便可以完成用户的各种指令
        // 服务器接收客户端发来的消息，然后完成对应指令
        train_t train;
        recv(netfd,&train.length,sizeof(train.length),MSG_WAITALL);
        recv(netfd,&train.data,train.length,MSG_WAITALL);
        printf("head_data：= %s\n",train.data);
        printf("head_length：= %d\n",train.length);
        char *p = train.data;

        recv(netfd,&train.length,sizeof(train.length),MSG_WAITALL);
        recv(netfd,&train.data,train.length,MSG_WAITALL);
        printf("data：=%s\n",train.data);
        printf("data_length：=%d\n",train.length);
        char *q = train.data;

        // 分类处理命令
        handle_command(p,q);
        close(netfd);
        printf("I worker finish!\n");

    }

}
// 创建子线程
int makeWorker(threadPool_t *pthreadPool)
{
    for(int i=0;i<pthreadPool->tidArr.workerNum;i++)
    {
        pthread_create(&pthreadPool->tidArr.arr[i],NULL,threadFunc,pthreadPool);
    }
    return 0;
}

